package com.qingyun.form.items

import android.view.View
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.core.view.isVisible
import com.qingyun.form.R
import com.qingyun.form.base.FormType
import com.qingyun.form.base.FormViewHolder

open class CheckBoxFormItem(
    label: String,
    name: String,
    value: String?,
    required: Boolean = false,
) : BaseFormItem(label, name, value), View.OnClickListener {
    override val formType: FormType
        get() = FormType.CheckBox
    override val layoutId: Int
        get() = R.layout.form_item_check_box

    protected open val checkLabels = arrayOf("是", "否")

    override var hint: String? = null
    open var checked: Boolean
        get() = this.value?.toBooleanStrict() == true
        set(value) {
            this.value = value.toString()
        }
    protected open val checkLabel: String
        get() = when (checked) {
            true -> checkLabels[0]
            false -> checkLabels[1]
        }

    init {
        this.required = required
    }

    open fun setCheckBoxLabel(checkLabel: String, uncheckLabel: String) {
        this.checkLabels[0] = checkLabel
        this.checkLabels[1] = uncheckLabel
    }

    override fun onBindViewHolder(holder: FormViewHolder) {
        holder.updateTitleLayout()
        holder.checkBox().apply {
            text = checkLabel
            isChecked = checked
            isVisible = !viewOnly
        }
        holder.setVisibility(R.id.tvValue, viewOnly)
        holder.setVisibility(R.id.tvHint, !this.hint.isNullOrEmpty() && !viewOnly)
        holder.setText(R.id.tvHint, this.hint)
        holder.setText(R.id.tvValue, checkLabel)
    }

    protected open fun FormViewHolder.checkBox(): CheckBox {
        return this.getView(R.id.cbValue)
    }

    override fun onBindViewEvent(holder: FormViewHolder) {
        super.onBindViewEvent(holder)
        holder.itemView.tag = holder.checkBox()
        holder.itemView.setOnClickListener(this)
        holder.checkBox().setOnCheckedChangeListener(::onCheckedChanged)
    }

    override fun onUnBindViewEvent(holder: FormViewHolder) {
        super.onUnBindViewEvent(holder)
        holder.itemView.setOnClickListener(null)
        holder.checkBox().setOnCheckedChangeListener(null)
    }

    override fun getTitleLayoutWidth(holder: FormViewHolder): Int {
        return holder.findTitleLayout().measuredWidth
    }

    protected fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        onValueChanged(isChecked.toString())
    }

    override fun onClick(v: View) {
        val tag = v.tag
        if (tag is CheckBox) {
            tag.isChecked = !tag.isChecked
        }
    }

}